import { BaseClass } from '../Managers/BaseClass';
import { NetConfig } from '../Managers/Net/NetCfg';
import { WECHAT } from 'cc/env';
import { GameTip } from '../Managers/TipMgr';
import { Size, game ,screen} from 'cc';

export const wx = window['wx'];

//微信平台
export class Platform extends BaseClass {
    private tempCode: string = "";//临时登录code
    private appid: string = NetConfig.wxAppid;
    // private secret: string = '';

    private grant_type: string = "authorization_code";//固定值
    private openId: string = "";//用户唯一id
    private session_key: string = "";//会话密钥

    public nickName: string = "";
    public avatarUrl: string = "";//头像url

    private loginSuccessCallback: any;
    private loginFailedCallback: any;
    private static _inst: Platform;
    // wx: any;
    public static get inst(): Platform {
        if (this._inst == null) {
            this._inst = new Platform();
        }
        return this._inst;
    }

    constructor(){
        super()
        if(!WECHAT){
            GameTip.inst.showTip('当前不是微信环境');
            return;
        }
        this.Init();
    }

    private Init(): void{
        // this.wx = window['wx'];

        // 显示分享菜单
        wx.showShareMenu({
            withShareTicket: true,
            menus: ['shareAppMessage', 'shareTimeline'],
        });
    }

    //微信获取本地数据
    public getStorageSync(key: string){
        let res = wx.getStorageSync(key);
        console.log('========getStorageSync=========',res)
        return res;
    } 

    //微信设置本地数据
    public setStorageSync(key: string,value:any){
        console.log('========setStorageSync=========',key,value)
        wx.setStorageSync(key,value)
    }

    //微信剪贴板
    public capyToClipBoard(str: string){
        console.log('=====capyToClipBoard 微信平台复制========',str)
        if(!WECHAT){
            GameTip.inst.showTip('当前不是微信环境');
            return;
        }
        wx.setClipboardData({
            data: str,
            success: () => {
                wx.showToast({
                    title: "复制成功",
                    icon: "none",
                    image: "",
                    duration: 1500
                })
            },
            fail: (err) => {
                wx.showToast({
                    title: "复制失败" + err,
                    icon: "none",
                    image: "",
                    duration: 1500
                })
            },
        });
    }
    
    //step0:登录流程
    public async LoginWX(){
        if(!WECHAT){
            GameTip.inst.showTip('当前不是微信环境');
            return;
        }
        let code = await this.getWxCode();
        console.log('=======LoginWX======',code);
        let data = await this.getServerForVerify(code.toString());
        if(data['code'] == '0'){
            this.openId = data['opId'];
            console.log('=======LoginWX1======', this.openId );
        }   

        let res = {
            openId:  this.openId,
            name:'',
            avator: '',
        }
        
        let userInfo = await this.getUseInfo2();
        console.log('=======userInfo=====',userInfo)
        res.name = userInfo['nickName'];
        res.avator = userInfo['avatarUrl'];
        return res;
    }
 
    //step1:调用 wx.login 接口获取 临时登录凭证code(时效5分钟)
    public getWxCode(){
        return new Promise((reject,resolve)=>{
            wx.login({
                timeout: 10000,         // 超时时间毫秒
                success: (res) => {
                    // 用户登录凭证，有效期5分钟
                    let code = res.code;        
                    console.log("登录获取凭证成功, code:", code);
                    reject(code)
                    // this.wx.request()
                },
                fail: (err) => {
                    console.log(`wx.login 失败, errorCode:${err.errno}, msg:${err.errMsg}`)
                    resolve(err);
                },
                complete:(res)=>{
                    console.log('===complete======',res)
                }
            });
        })
    }

    //step2: 将code发送给服务器校验,返回 openId
    private getServerForVerify(code: string){
        console.log('=====getServerForVerify1=======',code)
        return new Promise((reject,resolve)=>{
            wx.request({
                url: `https://${NetConfig.domain}/vfb/user-login/loginAg?code=${code}`,
                header: {
                    'content-type': 'application/json' // 请求头
                },
                timeout: 6000,
                method:'POST',
                success: (res) => {
                    console.log('获取数据成功', res.data);
                    reject(res.data);
                },
                fail: (err) => {
                    console.error('获取数据失败', err);
                    resolve(err);
                },
            })
        })
    }

    //step3_2: 获取微信的用户信息
    private getUseInfo2() {
        return new Promise((reject, resolve) => {
            wx.getSetting({
                success(res) {
                    if (res.authSetting['scope.userInfo']) {
                        // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                        wx.getUserInfo({
                            success: function (res) {
                                console.log(res.userInfo)
                                reject(res.userInfo)
                            }
                        })
                    } else {
                        //真机要使用这种方式
                        // 否则，先通过 wx.createUserInfoButton 接口发起授权
                        const canvasSize: Size = screen.windowSize;
                        let widget = canvasSize.width
                        let height = canvasSize.height;

                        console.log('========真机要使用这种方式=========',widget,height);
                        let button = wx.createUserInfoButton({
                            type: 'text',
                            text: '获取用户信息',
                            style: {
                                left: widget/2 - 200/2,
                                top: height/10*8,
                                width: 200,
                                height: 40,
                                lineHeight: 40,
                                backgroundColor: '#ff0000',
                                color: '#ffffff',
                                textAlign: 'center',
                                fontSize: 16,
                                borderRadius: 4
                            }
                        })
                        button.onTap((res) => {
                            // 用户同意授权后回调，通过回调可获取用户头像昵称信息
                            console.log('用户同意授权后回调 ', res.userInfo, res.errMsg)
                            if (res && res.userInfo) {
                                console.log("用户同意授权");
                                if (res.errMsg === "getUserInfo:ok") {
                                    reject(res.userInfo)
                                }
                                // 授权成功后，才销毁按钮
                                button.destroy();
                            }else{
                                console.log("用户拒绝授权");
                            }
                        })
                    }
                }
            })
        })
    }

    //分享游戏给好友
    public shareFriend( tit:string = '转发标题'){
        if(!WECHAT){
            GameTip.inst.showTip('当前不是微信环境');
            return;
        }
        return new Promise((reject,resolve)=>{
            wx.shareAppMessage({
                title: tit,
            });
        })
    }

    //分享游戏图片给好友
    public shareFriendImg() {
        if (!WECHAT) {
            GameTip.inst.showTip('当前不是微信环境');
            return;
        }
        console.log('========shareFriendImg===========')
        return new Promise((reject, resolve) => {
            console.log('========shareFriendImg1===========')
            let canvas:any = game.canvas;
            let tempFilePath = canvas.toTempFilePathSync();
            console.log('========shareFriendImg2===========',tempFilePath);
            wx.authorize({
                scope: 'scope.writePhotosAlbum',//这里表示相册权限
                success:  (res)=> {
                    //如果有授权过会直接返回成功，我们在这里就可以直接	调用保存图片的接口
                    wx.saveImageToPhotosAlbum({
                        filePath: tempFilePath,
                        success: function (res): void {
                            // window.wx.showToast({
                            //     title: "截图已保存至相册,快快分享到朋友圈吧",
                            //     icon: "none",
                            //     image: "",
                            //     duration: 1500
                            // })
                            console.log('=====authorize=saveImageToPhotosAlbum success======',res,tempFilePath);
                            // wx.downloadFile({
                            //     url: tempFilePath,
                            //     success: (res)=>{
                            //       // 只要服务器有响应数据，就会把响应内容写入文件并进入 success 回调，业务需要自行判断是否下载到了想要的内容
                            //       if (res.statusCode === 200) {
                            //         // wx.playVoice({
                            //         //   filePath: res.tempFilePath
                            //         // })
                            //         console.log('=====authorize=downloadFile success======',res);
                            //         wx.showToast({
                            //             title: "保存至相册成功！",
                            //             icon: "none",
                            //             image: "",
                            //             duration: 1500
                            //         })
                            //       }
                            //     }
                            // })
                        
                            //     wx.shareAppMessage({
                        //         imageUrl:tempFilePath
                        //    })
                        },
                        fail: function (err): void {
                            console.log('======authorize saveImageToPhotosAlbum fail======',err)
                        }
                    });
                },
                fail: ()=> {
                    //没有授权过，我们调用showModal弹出弹窗，告诉用户请求给予我们授权。
                    var alertParam = {
                        'title': '微信授权',
                        'content': '保存到相册需要您的授权，请给予我们授权',
                        'showCancel': true,
                        'canelColor': '#666',
                        'confirmText': '去授权',
                        'confirmColor': '#666',
                        success: function (ssa) {
                            //打开设置界面，设置界面只会出现小程序已经向用户请求过的权限。我们请求过保存图片的权限，所以里面会有相册的按钮，允许后点返回。则执行下面的success方法。调用保存图片的接口
                            if (ssa.confirm == true) {
                                    wx.openSetting({
                                    success: function () {
                                        wx.saveImageToPhotosAlbum({
                                            filePath: tempFilePath,
                                            success: function (res): void {
                                                // window.wx.showToast({
                                                //     title: "截图已保存至相册,快快分享到朋友圈吧",
                                                //     icon: "none",
                                                //     image: "",
                                                //     duration: 1500
                                                // })
                                            },
                                            fail: function (): void {
                                            }
                                        });
                                    }
                                })
                            }
                        }
                    };
                    //这里调用弹窗。
                    wx.showModal(alertParam);
                }
            })
        })
    }

    //邀请好友加入
    public shareFriendToJoin(param: string){
        return new Promise((reject,resolve)=>{
            wx.shareAppMessage({
                title: '邀请好友',
                // imageUrl: '分享图片URL',
                query: param,
            });
        })
    }
}


